//
//  MU_News_imageViewController.m
//  iNanKai
//
//  Created by apple on 12-12-3.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "MU_bigImagesViewController.h"
//#import  <SDWebImage/UIImageView+WebCache.h>
#import "MU_ZoomingScrollView.h"
#import "XDHeader.h"

@interface MU_bigImagesViewController ()<UIGestureRecognizerDelegate>
//@property (nonatomic,retain) UIImageView *imageView;
{
    UIView *tabView;
    UIView *topView;
    BOOL isClicked;
    UITapGestureRecognizer *singleTap;
    CGFloat lastScale;
    
}
@end

@implementation MU_bigImagesViewController
@synthesize urlArr=_urlArr;
@synthesize startIndex = _startIndex;
@synthesize info=_info;


- (void)viewDidLoad
{  
    [super viewDidLoad];
    
    isClicked = NO;
    //顶部工具条
//    UIToolbar* topBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, UI_SCREEN_HEIGHT-49, 320, 49)];
//    topBar.barStyle = UIBarStyleBlack;
//    [self.view addSubview:topBar];
//    
    self.view.backgroundColor = [UIColor colorWithRed:242.0/255.0 green:242.0/255.0 blue:242.0/255.0 alpha:1];//[UIColor blackColor];
    //左端返回按钮
//    UIBarButtonItem* back = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStyleBordered target:self action:@selector(backBtnClicked)];
    
    
    topView = [[UIView alloc]initWithFrame:CGRectMake(0,0, 320, 44)];
    topView.backgroundColor =[UIColor colorWithRed:242.0/255.0 green:242.0/255.0 blue:242.0/255.0 alpha:0.9];
    
    UIButton* backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(0, 0, 60, 44);
    [backBtn addTarget:self action:@selector(backBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    
    UIImageView *backIV = [[UIImageView alloc]initWithFrame:CGRectMake(10, 12, 15, 22)];
    backIV.image = [UIImage imageNamed:@"back_icon@2x"];
    [backBtn addSubview:backIV];
    
   
//    //右端保存按钮
//    UIBarButtonItem* save = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStyleBordered target:self action:@selector(saveTapHandler)];
//    //空隙
//    UIBarButtonItem* space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
//    //标题
//    UILabel* titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 30)];
//    titleLabel.backgroundColor = [UIColor clearColor];
//    titleLabel.textColor = [UIColor whiteColor];
//    titleLabel.tag = dTagTitleView;
//    UIBarButtonItem* titleItem = [[UIBarButtonItem alloc] initWithCustomView:titleLabel];
//    [topBar setItems:[NSArray arrayWithObjects:backItem, nil]];
//    titleLabel.textAlignment = NSTextAlignmentCenter;
    
    mLastScale=1.0;
    mCurrentScale=1.0;
    tScale=1.0;

    currentPage = 0;//初始显示的是哪张图片
  
    //将imagesArr添加到scrollView中显示
//    CGFloat toolBarHeight = CGRectGetHeight(topBar.frame);
    CGRect sframe = self.view.bounds;
    sframe.size.height = sframe.size.height;//减去导航栏
    sframe.origin.y = 0;
    scrollView = [[UIScrollView alloc] initWithFrame:sframe];
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.delegate = self;
    scrollView.pagingEnabled = YES;
    
    // 手势
    singleTap =[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(whenClickImage:)];
    
    singleTap.numberOfTapsRequired = 1;

    [scrollView addGestureRecognizer:singleTap];

    // 双击的 Recognizer
    UITapGestureRecognizer* doubleRecognizer;
    doubleRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(whenClickImage:)];
    doubleRecognizer.numberOfTapsRequired = 2; // 双击
    //关键语句，给self.view添加一个手势监测；
//    [scrollView addGestureRecognizer:doubleRecognizer];
    
    // 关键在这一行，双击手势确定监测失败才会触发单击手势的相应操作
//    [singleTap requireGestureRecognizerToFail:doubleRecognizer];
    
    
    [self.view addSubview:scrollView];
    
    int count = _urlArr.count;
    scrollView.contentSize = CGSizeMake(scrollView.frame.size.width * count, scrollView.frame.size.height);
    
    //菊花提示
    active = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, dSizeActiIndicator, dSizeActiIndicator)];
    active.center = scrollView.center;
    active.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
    [self.view addSubview:active];
    
    //scrollView.backgroundColor = [UIColor whiteColor];
    for (int i=0; i<count; i++) {
        //UIImageView* imgView = [[UIImageView alloc] initWithFrame:CGRectMake(i*scrollView.frame.size.width, 0, scrollView.frame.size.width, scrollView.frame.size.height)];
        MU_ZoomingScrollView* imgView = [[MU_ZoomingScrollView alloc] initWithFrame:CGRectMake(i*scrollView.frame.size.width, 0, scrollView.frame.size.width, scrollView.frame.size.height)];
        NSString* imgName = [_urlArr objectAtIndex:i];
        imgView.imageName = imgName;
        imgView.tag = 100+i;//设置tag便于之后保存的时候获取图片
        
       
        
        [scrollView addSubview:imgView];
    }
    [self showPageAtIndex:_startIndex];
    
    tabView = [[UIView alloc]initWithFrame:CGRectMake(0, UI_SCREEN_HEIGHT-49, 320, 49)];
    tabView.backgroundColor =[UIColor colorWithRed:242.0/255.0 green:242.0/255.0 blue:242.0/255.0 alpha:0.9];// RGBA(100, 100, 100, 0.5);
//    tabView.backgroundColor.
//    UIButton* backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    backBtn.frame = CGRectMake(0, 0, 60, 49);
//    [backBtn addTarget:self action:@selector(backBtnClicked) forControlEvents:UIControlEventTouchUpInside];
//    
//    UIImageView *backIV = [[UIImageView alloc]initWithFrame:CGRectMake(10, 12, 15, 22)];
//    backIV.image = [UIImage imageNamed:@"back_icon@2x"];
//    [backBtn addSubview:backIV];
    //[[UIButton alloc] initWithTitle:@"返回" style:UIBarButtonItemStyleBordered target:self action:@selector(backBtnClicked)];
    
    UIButton* saveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    saveBtn.frame = CGRectMake(140, 0, 60, 49);
    [saveBtn addTarget:self action:@selector(saveTapHandler) forControlEvents:UIControlEventTouchUpInside];
    
    UIImageView *saveIV = [[UIImageView alloc]initWithFrame:CGRectMake(10, 12, 22, 22)];
    saveIV.image = [UIImage imageNamed:@"download_icon@2x"];
    [saveBtn addSubview:saveIV];

    [tabView addSubview:saveBtn];
    [topView addSubview:backBtn];
    [self.view addSubview:tabView];
    [self.view addSubview:topView];
    
   
    
}

// 手势方法
-(void)whenClickImage:(UITapGestureRecognizer*)sender

{
    
    DDLOG(@"you click image");
    if (sender.numberOfTapsRequired==1) {
        isClicked = !isClicked;
        if (isClicked) {
            SETSTATUSBARHIDDEN(YES);
            [UIView animateWithDuration:.3 animations:^{
                tabView.frame = CGRectMake(0, UI_SCREEN_HEIGHT, 320, 49);
                topView.frame = CGRectMake(0, -44, 320, 44);
            }];
        }else{
            SETSTATUSBARHIDDEN(YES);
            [UIView animateWithDuration:.3 animations:^{
                tabView.frame = CGRectMake(0, UI_SCREEN_HEIGHT-49, 320, 49);
                topView.frame = CGRectMake(0, 0, 320, 44);
            }];
        }

    }
    else{
        DDLOG(@"双击");
        

    }
    
    
    
//    [self presentViewController:imageviewcontroller animated:YES completion:nil];
    
}


-(void)saveTapHandler
{
    if (![active isAnimating]) 
    {
        [active startAnimating];
        //获取当前显示的图片，保存到相册
//        UIImageView* imgView = (UIImageView*)[scrollView viewWithTag:100+currentPage];
        MU_ZoomingScrollView* imgView = (MU_ZoomingScrollView*)[scrollView viewWithTag:100+currentPage];
        UIImageView* imageView = imgView.imageView;
        UIImageWriteToSavedPhotosAlbum(imageView.image, self, @selector(imageSavedToPhotoAlbum:didFinishSavingWithError:contextInfo:), nil);
    }
}
-(void)imageSavedToPhotoAlbum:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
     NSString *message;
     NSString *title;
    [active stopAnimating];
    if(!error)
    {
        [self showMBProgressWithText:@"图片已成功保存到相册"];//保存成功
    }
     else {
         title=@"啊哦,图片保存失败";
         message=[error description];
         UIAlertView *alert=[[UIAlertView alloc]initWithTitle:title message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
         [alert show];
     }
    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    active = nil;
    scrollView = nil;
    progressBar = nil;
    self.urlArr = nil;
    self.info = nil;
}

#pragma mark -- btn callbacks
-(void)backBtnClicked
{
    //返回
    SETSTATUSBARHIDDEN(NO);
    [self dismissViewControllerAnimated:YES completion:nil];//:YES];
}


#pragma mark - scrollView delegates
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scroll
{
//    CGPoint offset = scroll.contentOffset;
//    CGRect bounds = scroll.frame;
//    
//    int newPage = offset.x/bounds.size.width;
//    NSLog(@"newsPage = %i",newPage);
//    currentPage = newPage;
    
    CGFloat pageWidth = scrollView.frame.size.width;
	NSInteger page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
	//NSLog(@"page = %d, lastPage = %d", page, lastPage);
	
	if (currentPage != page)
	{
		MU_ZoomingScrollView *aView = (MU_ZoomingScrollView *)[scroll viewWithTag:100+currentPage];
		aView.zoomScale = 1.0;
		
		currentPage = page;
        [self changeTitleToIndex:currentPage];
	}
}


#pragma mark - procedure methods
-(void)showPageAtIndex:(int)index
{
    //显示scrollView的第几页
    [self changeTitleToIndex:index];

    CGSize viewSize = scrollView.frame.size;
    CGRect rect = CGRectMake(index* viewSize.width, 0, viewSize.width, viewSize.height);
    [scrollView scrollRectToVisible:rect animated:YES];
}

-(void)changeTitleToIndex:(int)index
{
    //标题提示第几页
//    UILabel* titleLabel = (UILabel*)[self.view viewWithTag:dTagTitleView];
//    NSString* title = [NSString stringWithFormat:@"%i/%i",index+1, _urlArr.count];
//    titleLabel.text = title;
}

-(void)showMBProgressWithText:(NSString*)text
{
    progressBar= [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    // Configure for text only and offset down
    progressBar.mode = MBProgressHUDModeText;
    progressBar.labelText = text;
    progressBar.margin =10.f;//提示框的边缘大小
    progressBar.removeFromSuperViewOnHide = YES;
    progressBar.animationType=MBProgressHUDAnimationFade;
    [progressBar hide:YES afterDelay:1.0];//显示时间1s
    progressBar.yOffset=80;
    
}
@end

